package thread;

/**
 * @User: vitobo
 * @Date: 2024-07-25
 * @Description:  线程中断: 使用Thread自带的标志位来进行判定；
 *      3种线程终止情况:     1)忽略终止请求;    2)加上break, 就会立即终止;  3)稍后进行终止;
 */
public class ThreadDemo9 {

    // 稍后进行终止;
    public static void main(String[] args) throws InterruptedException {
        Thread t = new Thread(()->{
            while (!Thread.currentThread().isInterrupted()){
                System.out.println("hello thread!");

                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException ex) {
                        throw new RuntimeException(ex);
                    }
                    break;
                }

            }
        });

        t.start();

        Thread.sleep(3000);
        t.interrupt();
    }

    // 加上break, 就会立即终止
    public static void main2(String[] args) throws InterruptedException {
        Thread t = new Thread(()->{
            while (!Thread.currentThread().isInterrupted()){
                System.out.println("hello thread!");

                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    break;
                }

            }
        });

        t.start();

        Thread.sleep(3000);
        t.interrupt();
    }

    // 1.忽略终止请求
    public static void main1(String[] args) {
        Thread t = new Thread(()->{
            // currentThread()  Thread类的静态方法, 通过这个方法可以获取到当前线程, 哪个线程调用这个方法, 就得到哪个线程的对象引用(类似于this)
            // Thread.currentThread() 是在t.run中被调用的,此处获取的线程就是t线程;
            // isInterrupted() 为 true表示被终止, 为false表示未被终止
            while (!Thread.currentThread().isInterrupted()){
                System.out.println("hello thread!");

                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }

            }
        });

        t.start();
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        // t.interrupt(); 终止t线程;
        // interrupt()会做两件事:
        //      1.把线程内的标志位会设置成true;
        //      2.如果线程再进行sleep, 就会触发异常,把sleep唤醒;  但是sleep在唤醒的时候, 还会做一件事, 把刚才设置的这个标志位,再设置回false(清空了标志位)
        t.interrupt();
    }
}
